Formatting Input and Output in C++: How to Control Output Style with cout

This article introduces how to adjust the output style of `cout` using format manipulators from the `<iomanip>` header in C++. The code should include `<iostream>` and `<iomanip>` and use `using namespace std`. For integer output, different number bases can be switched via `dec` (decimal, default), `hex` (hexadecimal), and `oct` (octal). The setting persists until manually reset (e.g., `cout << hex << 10;` outputs `a`). Floating-point formatting includes: - `fixed` for fixed decimal places (used with `setprecision(n)` to retain `n` decimal digits, e.g., `3.142`); - `scientific` for scientific notation (e.g., `1.235e+04`); - `setprecision(n)` controls significant figures by default, but switches to decimal places when combined with `fixed` or `scientific`. For alignment and width: - `setw(n)` sets the output width (only affects the next item); - `left`/`right` control alignment (default is right-aligned); - `setfill(c)` sets the fill character (e.g., `*`). Finally, distinguish `endl` (newline + buffer flush) from `\n` (newline only). Manipulators can be flexibly combined.

Read More